#!/usr/bin/php -q
<?php
// 新增相片
require_once("foto.inc.php");


if (!file_exists($otpw_cache)) {
	echo "[add_pic] no otpw cache, abort\n";
	exit;
}

$otpw=getotpwcache();

$album_id = $_SERVER['ab_id'];
if (empty($argv[1] )  || empty($album_id)) {
	printf("Usage: %s file [title=] [desc=]\n\tand setenv ab_id\n",
		$argv[0]);
	// last match if public and passwd exists
	exit;
}
$fpath=$argv[1];
$title="";
$desc ="";
$resize="";
// $album_id = intval($argv[2]);
for($i=1;$i<$argc;$i++) {
	if (strstr($argv[$i] , "=")) {
		list($key, $val) = explode("=",$argv[$i]);
		switch($key) {
			case 'desc':
				$desc = $val; break;
			case 'title':
				$title = $val; break;
			case 'resize':
				$resize = $val; break;
		}
	}
}
// 先檢查檔案是否存在
if (!file_exists($fpath)) {
		echo "[add_pic] file $fpath does not exist\n";
		exit;
}
if (!stristr($fpath, ".jpg") && !stristr($fpath, ".png")  &&  !stristr($fpath, ".gif")) {
	echo "[add_pic] unsupport file format: $fpath\n";
	exit;
}


// 如果需要 resize 的話
if (preg_match("/^\d+$/",$resize)) {
	$newfpath = '/tmp/' .$fpath;
	$cmd = sprintf("convert %s -thumbnail %dx%d %s",$fpath, $resize, $resize, $newfpath);
	exec($cmd);
	$fpath = $newfpath;
	$todel = $newfpath;
}

if (add_pic($otpw,$album_id, $fpath, $title, $desc)) {
	echo "[add_pic] picture $fpath add successful\n";
	@unlink($todel);
}

exit;
if (add_ab($otpw, $title, $desc, $vis, $pass, $is_review, $is_cp )) {
	// 成功新增
	$a = list_ab($otpw);
	foreach($a as $aid => $atitle) {
		$album_id = $aid;
		$album_title = $atitle;
		break;
	}
	printf("[add_ab] create album %d %s successful\n",$album_id,$album_title);
}

?>
